package com.qf.commons;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
public class BloomUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //初始化布隆过滤器的脚本
    private String reserveLua = "return redis.call('bf.reserve', KEYS[1], ARGV[1], ARGV[2])";
    //添加脚本
    private String addLua = "return redis.call('bf.add', KEYS[1], ARGV[1])";
    //判断是否存在的脚本
    private String existsLua = "return redis.call('bf.exists', KEYS[1], ARGV[1])";


    /**
     * 初始化bloom过滤器
     * @param key
     * @param d
     * @param cap
     */
    public void bloomInit(String key, double d, long cap){
        redisTemplate.execute(
                new DefaultRedisScript<>(reserveLua),
                Collections.singletonList(key),
                d + "", cap + "");
    }

    /**
     * 添加元素到bloom过滤器
     * @return
     */
    public boolean bloomAdd(String key, String value){

        Long result = redisTemplate.execute(
                new DefaultRedisScript<Long>(addLua, Long.class),
                Collections.singletonList(key),
                value);

        return result == 1;
    }

    /**
     * 判断是否存在
     * @param key
     * @param value
     * @return
     */
    public boolean bloomExists(String key, String value){
        Long result = redisTemplate.execute(
                new DefaultRedisScript<Long>(existsLua, Long.class),
                Collections.singletonList(key),
                value);

        return result == 1;
    }
}
